package servlets;

import hibernatelogic.HibUsers;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import orm.Users;

@WebServlet("/login-servlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final String docType = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 "
			+ "Transitional//EN\">\n";
	private static final Logger loggerLoginServlet = Logger
			.getLogger(LoginServlet.class);

	public LoginServlet() {
		super();
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		PrintWriter out = new PrintWriter(response.getWriter());

		/*
		 * Requesting parameters
		 */
		String login = request.getParameter("login");
		String password = request.getParameter("password");

		HibUsers hibUser = new HibUsers();

		/*
		 * Variable for userID 0 - doesn't exist >0 - user exists
		 */
		int allOK = 0;

		try {
			// Does user really exists
			allOK = hibUser.userExists(login, password);

			HttpSession sess = request.getSession();

			// If exists
			if (allOK != 0) {
				// Creating new Users object with known id
				Users tmpUser = hibUser.getUserByID(allOK);

				// Synchronizing session
				synchronized (sess) {
					// If just created
					if (sess.isNew()) {

						// String equivalent of role and user id
						String currentRole = String.valueOf(tmpUser.getRole());
						String currentID = String.valueOf(allOK);

						// Store user information at session attributes
						sess.setAttribute("UserID", currentID);
						sess.setAttribute("UserName", tmpUser.getName());
						sess.setAttribute("UserLogin", tmpUser.getLogin());
						sess.setAttribute("UserPassword", tmpUser.getPassword());
						sess.setAttribute("UserRole", currentRole);

						// Get roles to know, where we have to redirect the user
						switch (tmpUser.getRole()) {
						// in case of role = user
						case (1):
							response.sendRedirect("/my-pet-project-0/UserStartPage.jsp");
							break;
						// in case of role = manager
						case (2):
							response.sendRedirect("/my-pet-project-0/ManagerStartPage.jsp");
							break;
						// in case of role = administrator
						case (3):
							response.sendRedirect("/my-pet-project-0/AdminStartPage.jsp");
							break;
						// in case of some troubles
						default:
							response.sendRedirect("/my-pet-project-0/Login.jsp");
							break;
						}
					} else {
						// If session was old
						response.sendRedirect("/my-pet-project-0/Login.jsp");
					}
				}

				// If we did not found any users with known login/password
			} else {
				out.println(docType +
						"<html>\n<head>" +
						"<title>Connection page</title>" +
						"</head>\n<body><center>" +
						"<h1>Authorization page" +
						"</h1><center>");
				out.println("<center><h2>" +
						"We are sorry, you are not registered." +
						"<br>" +
						"Please, contact our system administrator" +
						"</h2></center>");
				out.println("<center><h5>" +
						"For more details you can send us a " +
						"<a href=\"mailto:081krieger@xakep.ru\">email</a> " +
						"or go <a href=/my-pet-project-0/Login.jsp>back</a>" +
						"</h5></center>");
				out.println("</body></html>");
			}
		} catch (Exception e) {
			loggerLoginServlet.error("Something wrong with LoginServlet", e);
		}
	}
}
